package cn.sinata.wanglin.neighbor.fragment;

import android.app.Activity;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.hyphenate.EMMessageListener;
import com.hyphenate.chat.EMClient;
import com.hyphenate.chat.EMCmdMessageBody;
import com.hyphenate.chat.EMMessage;
import com.hyphenate.easeui.EaseConstant;
import com.hyphenate.easeui.controller.EaseUI;
import com.xilada.xldutils.adapter.BaseRecyclerAdapter;
import com.xilada.xldutils.fragment.BaseLazyFragment;
import com.xilada.xldutils.utils.ActivityUtil;
import com.xilada.xldutils.utils.DensityUtil;
import com.xilada.xldutils.utils.SharedPreferencesUtils;
import com.xilada.xldutils.utils.Utils;
import com.xilada.xldutils.view.SwipeRefreshRecyclerLayout;
import com.yqritc.recyclerviewflexibledivider.HorizontalDividerItemDecoration;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import cn.sinata.wanglin.MyApplication;
import cn.sinata.wanglin.R;
import cn.sinata.wanglin.adapter.ContactAdapter;
import cn.sinata.wanglin.commonutils.Constant;
import cn.sinata.wanglin.db.dao.PushDao;
import cn.sinata.wanglin.db.dao.UserDao;
import cn.sinata.wanglin.model.Contact;
import cn.sinata.wanglin.neighbor.activity.ChatActivity;
import cn.sinata.wanglin.neighbor.activity.GroupListActivity;
import cn.sinata.wanglin.neighbor.activity.NewFriendsActivity;
import cn.sinata.wanglin.neighbor.activity.VillageNeighborActivity;
import cn.sinata.wanglin.neighbor.view.SearchEditText;
import cn.sinata.wanglin.net.HttpManager;
import cn.sinata.wanglin.net.model.ResultData;
import cn.sinata.wanglin.net.model.util.ResultSubscriber;
import cn.sinata.wanglin.utils.ContactUtils;
import cn.sinata.wanglin.view.BladeView;
import cn.sinata.wanglin.village.activity.ChoiceVillageActivity;
import rx.Observable;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;
import rx.functions.Func1;
import rx.functions.Func2;
import rx.schedulers.Schedulers;

/**
 * 通讯录
 * Created by liaoxiang on 16/12/9.
 */

public class ContactsFragment extends BaseLazyFragment implements SwipeRefreshRecyclerLayout.OnRefreshListener,EMMessageListener{

    @BindView(R.id.mSwipeRefreshLayout)
    SwipeRefreshRecyclerLayout mSwipeRefreshLayout;
    @BindView(R.id.mLetterListView)
    BladeView mLetterListView;
    TextView tv_unReadNewFriendMsg;
    private ContactAdapter contactAdapter;
    private ArrayList<Contact> mContacts = new ArrayList<>();
    private HashMap<String,Integer> letters = new HashMap<>();
    private String userID;
    private String account;
    private String housingId;

    protected RecyclerView.Adapter setAdapter() {
        contactAdapter = new ContactAdapter(mContacts);
        View headerView = LayoutInflater.from(context).inflate(R.layout.header_contact_layout,null);
        final SearchEditText tv_search = (SearchEditText) headerView.findViewById(R.id.tv_search);
        View fl_new_friend = headerView.findViewById(R.id.fl_new_friend);
        TextView tv_new_friends = (TextView) headerView.findViewById(R.id.tv_new_friends);
        TextView tv_neighbors = (TextView) headerView.findViewById(R.id.tv_neighbors);
        TextView tv_groups = (TextView) headerView.findViewById(R.id.tv_groups);
        tv_unReadNewFriendMsg = (TextView) headerView.findViewById(R.id.tv_unReadNewFriendMsg);
        int size = DensityUtil.dip2px(context,40);
        Drawable friendDrawable = ContextCompat.getDrawable(context,R.mipmap.ic_contact_friends);
        friendDrawable.setBounds(0,0,size,size);
        tv_new_friends.setCompoundDrawables(friendDrawable,null,null,null);
        Drawable neighborsDrawable = ContextCompat.getDrawable(context,R.mipmap.ic_contact_neighbors);
        neighborsDrawable.setBounds(0,0,size,size);
        tv_neighbors.setCompoundDrawables(neighborsDrawable,null,null,null);
        Drawable groupsDrawable = ContextCompat.getDrawable(context,R.mipmap.ic_contact_groups);
        groupsDrawable.setBounds(0,0,size,size);
        tv_groups.setCompoundDrawables(groupsDrawable,null,null,null);
        ViewGroup.LayoutParams params = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        headerView.setLayoutParams(params);
        contactAdapter.setHeaderView(headerView);

        tv_search.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                contactAdapter.getFilter().filter(s.toString().trim());
            }
        });

        tv_search.setOnSearchActionListener(new SearchEditText.OnSearchActionListener() {
            @Override
            public void onSearch() {
                contactAdapter.getFilter().filter(tv_search.getText().toString().trim());
            }
        });

        fl_new_friend.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ActivityUtil.create(ContactsFragment.this)
                        .go(NewFriendsActivity.class)
                        .start();
            }
        });
        tv_new_friends.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                ActivityUtil.create(ContactsFragment.this)
                        .go(NewFriendsActivity.class)
                        .start();

            }
        });
        tv_neighbors.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String housingId = SharedPreferencesUtils.getString(Constant.SP_HOUSING_ID);
                ActivityUtil.create(ContactsFragment.this)
                        .go(VillageNeighborActivity.class)
                        .put("id",housingId)
                        .put("type",1)
                        .start();

            }
        });
        tv_groups.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (MyApplication.houseid == null || MyApplication.houseid.equals("-1")) {
                    ActivityUtil.create(context)
                            .go(ChoiceVillageActivity.class)
                            .startForResult(0);
                } else {
                    ActivityUtil.create(ContactsFragment.this)
                            .go(GroupListActivity.class)
                            .start();
                }

            }
        });
        contactAdapter.setOnItemClickListener(new BaseRecyclerAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, int position) {
                Contact contact = mContacts.get(position);
                UserDao.getInstance(context).saveUser(contact.getAccount(),contact.getName(),contact.getHeadUrl());
                ActivityUtil.create(ContactsFragment.this)
                        .go(ChatActivity.class)
                        .put(EaseConstant.EXTRA_CHAT_TYPE,EaseConstant.CHATTYPE_SINGLE)
                        .put(EaseConstant.EXTRA_USER_ID,contact.getAccount())
                        .startForResult(5);
            }
        });
        return contactAdapter;
    }

    @Override
    protected int getContentViewLayoutID() {
        return R.layout.contacts_layout;
    }

    @Override
    protected void onFirstVisibleToUser() {

        userID = SharedPreferencesUtils.getString(Constant.SP_USERID);
        account = SharedPreferencesUtils.getString(Constant.SP_IM_ACCOUNT);

        mSwipeRefreshLayout.setLayoutManager(new LinearLayoutManager(context));
        mSwipeRefreshLayout.setMode(SwipeRefreshRecyclerLayout.Mode.Top);
        mSwipeRefreshLayout.setAdapter(setAdapter());
        mSwipeRefreshLayout.setOnRefreshListener(this);
        mSwipeRefreshLayout.addItemDecoration(new HorizontalDividerItemDecoration.Builder(context)
                .colorResId(R.color.dividing_line_color)
                .marginResId(R.dimen.activity_horizontal_margin, R.dimen.activity_horizontal_margin)
                .size(1)
                .build());

        mLetterListView.setOnItemClickListener(new BladeView.OnItemClickListener() {
            @Override
            public void onItemClick(String s) {
                selectRecyclerView(s);
            }
        });
        if (MyApplication.houseid == null || TextUtils.equals("-1", MyApplication.houseid)) {
            ActivityUtil.create(this)
                    .go(ChoiceVillageActivity.class)
                    .startForResult(0);
        } else {
            housingId = MyApplication.houseid;
            showDialog();
            getData();
        }
        EMClient.getInstance().chatManager().addMessageListener(this);
        unReadSet();
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Activity.RESULT_OK) {
            if (requestCode == 0 || requestCode == 3) {
                housingId = MyApplication.houseid;
                showDialog();
                getData();
            }
        }
        if (resultCode == Constant.ResultCode_CANCEL_FRIEND) {
            showDialog();
            getData();
        }
    }

    private void getData(){

        HttpManager.getFriendList(userID,housingId)
                .flatMap(new Func1<ResultData<ArrayList<Contact>>, Observable<Contact>>() {
                    @Override
                    public Observable<Contact> call(ResultData<ArrayList<Contact>> arrayListResultData) {
                        if (arrayListResultData.getCode().equals("SUCCESS")) {
                            ArrayList<Contact> contacts = arrayListResultData.getData();
                            for (Contact contact : contacts) {
                                String letter = ContactUtils.formatNamePy(contact.getName());
                                contact.setFirstChar(letter);
                            }
                            return Observable.from(contacts);
                        }
                        return Observable.error(new Throwable(arrayListResultData.getMessage()));
                    }
                })
                .toSortedList(new Func2<Contact, Contact, Integer>() {
                    @Override
                    public Integer call(Contact contact, Contact contact2) {
                        if (contact.getFirstChar().equals(contact2.getFirstChar())) {
                            return contact.getName().compareTo(contact2.getName());
                        } else {
                            if ("#".equals(contact.getFirstChar())) {
                                return -1;
                            } else if ("#".equals(contact2.getFirstChar())) {
                                return 1;
                            }
                            return contact.getFirstChar().compareTo(contact2.getFirstChar());
                        }
                    }
                })
                .doOnNext(new Action1<List<Contact>>() {
                    @Override
                    public void call(List<Contact> contacts) {

                        for (int i = 0; i < contacts.size(); i++) {
                            Contact contact = new Contact();
                            contact.setHeadIndex(i);
                            contact.setFirstChar(contacts.get(i).getFirstChar());
                            contact.setName(contacts.get(i).getName());
                            if(!letters.containsKey(contacts.get(i).getFirstChar())){
                                letters.put(contacts.get(i).getFirstChar(),i);
                            }
                        }
                    }
                })
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new ResultSubscriber<List<Contact>>(this){
                    @Override
                    public void onNext(List<Contact> contacts) {
                        super.onNext(contacts);
                        mSwipeRefreshLayout.setRefreshing(false);
                        dismissDialog();
                        mContacts.clear();
                        if (contacts.size() == 0) {
                            mSwipeRefreshLayout.setLoadMoreText("没有好友");
                        }
                        mContacts.addAll(contacts);
                        contactAdapter.setLetters(letters);
                        contactAdapter.notifyDataSetChanged();
                    }

                    @Override
                    public void onError(Throwable e) {
                        super.onError(e);
                        mSwipeRefreshLayout.setRefreshing(false);
                        dismissDialog();
                        showToast(e.getMessage());
                    }
                });
    }

    @Override
    protected void onVisibleToUser() {
        housingId = MyApplication.houseid;
        Utils.systemErr("--onVisibleToUser-->");
        unReadSet();
    }

    void unReadSet(){
        int count = PushDao.getInstance(context).getUnReadNum(account,Constant.Push.CMD_MEG_TYPE_F);
        Utils.systemErr("---->"+count);
        if (count > 0) {
            tv_unReadNewFriendMsg.setVisibility(View.VISIBLE);
        } else {
            tv_unReadNewFriendMsg.setVisibility(View.GONE);
        }
    }

    @Override
    protected void onInvisibleToUser() {

    }

    @Override
    public void onRefresh() {
        if (MyApplication.houseid == null || TextUtils.equals("-1", MyApplication.houseid)) {
            mSwipeRefreshLayout.setRefreshing(false);
            ActivityUtil.create(this)
                    .go(ChoiceVillageActivity.class)
                    .startForResult(0);
        } else {
            getData();
        }
    }

    @Override
    public void onLoadMore() {
        mSwipeRefreshLayout.setRefreshing(false);
    }

    private void selectRecyclerView(String s) {
        if (s.equals("↑") || s.equals("#")) {
            mSwipeRefreshLayout.getRecyclerView().scrollToPosition(0);
        } else {
            if(letters.containsKey(s)){
                mSwipeRefreshLayout.getRecyclerView().scrollToPosition(letters.get(s));
            }
        }
    }

    @Override
    public void onMessageReceived(List<EMMessage> list) {

    }

    @Override
    public void onCmdMessageReceived(List<EMMessage> list) {
        if (getActivity() != null && !isDetached()) {
            getActivity().runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    unReadSet();
                }
            });
        }
    }

    @Override
    public void onMessageReadAckReceived(List<EMMessage> list) {

    }

    @Override
    public void onMessageDeliveryAckReceived(List<EMMessage> list) {

    }

    @Override
    public void onMessageChanged(EMMessage emMessage, Object o) {

    }
}
